import React from 'react'
import UrlPattern from 'url-pattern'
import { connect } from 'react-redux'
import { Col, Row, Icon,Modal } from 'antd'
import { TwsBelongTask } from 'tws-antd'

import { studentAssignmentPageBodyUrl } from '../constant/constant-url'
import ReferenceButtonGroup from './assignment/reference-button-group'
import EditStatusBox from './assignment/edit-status-box'
import CommentBox from './assignment/comment-box'
import Homework from './assignment/homework-quiz'
import * as actions from '../actions/homework'
import { studentGetSectionComments } from '../actions/comment'
import { getReviewHomeworkQuiz, submitSupplementary } from '../actions/reviewQuiz'
import AssignmentSupplementaryBox from './assignment/assignment-supplementary-box'
import { addNotification } from '../actions/notification'
import { FormattedMessage } from 'react-intl'
import { getAssignmentDuration } from '../actions/homework'
import { startAssignment } from '../actions/homework'
import { convertContent } from '../constant/lang-util'

class HomeworkDetailPageBody extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      programId: 0,
      taskId: 0,
      assignmentId: 0,
      quizId: 0
    }
  }
  loadData = () => {
    const {history, location} = this.props
    const {assignmentId, taskId} = this.props.match.params
    history.listen(this.update.bind(this))
    this.update(location)
    this.props.getHomeworkQuizzes(assignmentId)
    this.props.getTask(taskId)
  }

  showStartModal = () => {
    Modal.info({
      title: convertContent('确定开始答题？'),
      okText: convertContent('确定'),
      onOk: () => {
        this.startAssignment()
        this.loadData()
      },
    })
  }

  startAssignment = () => {
    const {assignmentId, taskId} = this.props.match.params
    const {user} = this.props
    this.props.startAssignment(user.id, taskId, assignmentId)
  }

  componentDidMount () {
    const {assignmentId, taskId} = this.props.match.params
    this.props.getAssignmentDuration(taskId, assignmentId, (assignmentDuration) => {
      if (assignmentDuration.id) {
        this.loadData()
      } else {
        this.showStartModal()
      }
    })
  }

  update (location) {
    const pattern = new UrlPattern(studentAssignmentPageBodyUrl)
    const urlParams = pattern.match(location.pathname) || {}
    const {taskId, programId, assignmentId, quizId} = urlParams

    this.setState({
      taskId,
      programId,
      assignmentId,
      quizId
    })
    if (quizId) {
      this.props.getReviewQuiz(assignmentId, quizId)
      this.props.getComments(assignmentId, quizId)
    }
  }

  render () {
    const {taskId, programId, assignmentId, quizId} = this.state
    const {review, quizzes, task, settings, suggestions, submission, user} = this.props
    const {studentWebUrl} = settings
    const quiz = quizzes.find(item => item.id === parseInt(quizId, 10)) || {}
    const assignment = task.assignments.find(assignment => assignment.id === parseInt(assignmentId, 10)) || {}

    return <div>
      <Row className='margin-t-2'>
        <Col offset={1} span={22}>
          <div>
            <Row>
              <Col xs={24} sm={24} md={24} lg={9} xl={8}>
                <h2>{assignment.title || ''}</h2>
              </Col>
              <Col xs={24} sm={24} md={24} lg={9} xl={11}>
                {programId
                  ? <ReferenceButtonGroup
                    review={review}
                    programId={programId}
                    quizId={quiz.id}
                    taskId={taskId}
                    assignmentId={assignmentId}
                    quizDefinition={quiz} />
                  : ''
                }
              </Col>
              <Col xs={24} sm={12} md={12} lg={6} xl={5}>
                <EditStatusBox
                  disable
                  review={review}
                  updateReviewQuiz={this.props.updateReviewQuiz}
                  assignmentId={assignmentId}
                  quizId={quiz.id} />
              </Col>
            </Row>
          </div>
          {
            quiz.id && user.id
              ? <Homework
                finished
                studentId={user.id}
                submission={submission}
                quiz={quiz}
                settings={settings}
                reviewQuiz={review}
                taskId={taskId}
                assignmentId={assignmentId}
                programId={programId}
                getHomeworkQuizzes={this.props.getHomeworkQuizzes}
                addNotification={this.props.addNotification}
                submitAnswer={this.props.submitAnswer}
                submitQuizSuggestion={this.props.submitQuizSuggestion}
                getRunningLogs={this.props.getRunningLogs} />
              : ''
          }
          <TwsBelongTask title={<FormattedMessage id='所属任务卡' />}>
            <a href={studentWebUrl + '/program/' + this.state.programId + '/task/' + this.state.taskId}>
              <Icon type='arrow-left' />{task.title}
            </a>
          </TwsBelongTask>
          {
            review.id
              ? <AssignmentSupplementaryBox
                submitSupplementary={this.props.submitSupplementary}
                reviewQuiz={review}
                assignmentId={assignmentId} />
              : ''
          }
          <CommentBox
            user={this.props.user}
            studentId={this.props.user.id}
            suggestions={suggestions}
            programId={this.state.programId}
            taskId={this.state.taskId}
            quizId={this.state.quizId}
            assignmentId={this.state.assignmentId}
          />
        </Col>
      </Row>
    </div>
  }
}

const mapStateToProps = ({user, homeworkQuizzes, review, comments, task, submission, settings}) => {
  return {
    user,
    review,
    quizzes: homeworkQuizzes,
    task,
    suggestions: comments,
    submission,
    settings
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    getHomeworkQuizzes: (assignmentId) => dispatch(actions.getHomeworkQuizzes(assignmentId)),
    getReviewQuiz: (assignmentId, quizId) => dispatch(getReviewHomeworkQuiz(assignmentId, quizId)),
    getComments: (assignmentId, quizId) => dispatch(studentGetSectionComments(assignmentId, quizId)),
    getTask: (taskId) => dispatch(actions.getTask(taskId)),
    submitAnswer: (data, callback) => dispatch(actions.submitAnswer(data, callback)),
    submitQuizSuggestion: (quizSuggestion, callback) => dispatch(actions.submitQuizSuggestion(quizSuggestion, callback)),
    getRunningLogs: (userId, assignmentId, quizId) => dispatch(actions.getRunningLogs(userId, assignmentId, quizId)),
    addNotification: (data) => dispatch(addNotification(data)),
    submitSupplementary: (id, supplement) => dispatch(submitSupplementary(id, supplement)),
    getAssignmentDuration: (taskId, assignmentId, callback) => dispatch(getAssignmentDuration(taskId, assignmentId, callback)),
    startAssignment: (userId, taskId, assignmentId) => dispatch(startAssignment(userId, taskId, assignmentId)),

  }
}

export default connect(mapStateToProps, mapDispatchToProps)(HomeworkDetailPageBody)
